package com.example.databasehomework;

import static com.example.databasehomework.HttpUnit.getAllCourse;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.slidingpanelayout.widget.SlidingPaneLayout;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Activity_home extends AppCompatActivity {

    public static final int ALLCOURSE = 1, ALLEXP = 2, EXP = 3, ADD_S = 114, ADD_CC = 514;

    private RecyclerView recyclerView;
    private List<MainListItemBean> exp_data, course_data;
    private MainListAdapter exp_adapter, course_adapter;
    private AlertDialog.Builder addExpBuilder, addCourseBuilder, chooseCRoomBuilder, deletExpOrCourseBuilder, addRoomBuilder;
    private AlertDialog addExp, addCourse, chooseCRoom, deletExpOrCourse, addRoom;
    private View viewAddExp, viewAddCourse, viewChooseCRoom, viewDeletExpOrCourse, viewAddRoom, mLeftView, mMainView;
    private SlidingPaneLayout slidingPaneLayout;
    private FloatingActionsMenu fm;
    private FloatingActionButton fb_refresh, fb_addexp;
    private ConstraintLayout head, exit, course, editinfo, exp, addroom, signup, addStudents, addCChoose;
    private ImageView course_img, exp_img;
    private TextView course_text, exp_text, headText;

    private String[] seasons = {"秋季", "春季", "夏季"};

    private int status;
    private String courseId;
    private String expId, expName;

    private List<String> roomIds;
    private RoomListAdapter roomAdapter;

    private List<ChooseRoomListItemBean> allRoomIds;
    private ChooseRoomListAdapter allRoomAdapter;

    private String uInfo;

    private  final int REQUEST_EXTERNAL_STORAGE = 1;
    private  String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    public  void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        verifyStoragePermissions(Activity_home.this);
        getItems();
        setText();
        setSlidingStyle();          //设置侧边栏滑动效果
        setLeftButtons();           //设置侧边栏按钮监听器
        setLeftCourse();
        setHeadButtonListener();    //设置主界面HEAD按钮监听器
        initViewItemListener();
        initView();                 //初始化列表
        initAddExp();               //初始化加实验的窗口
        initAddCourse();
        initChooseCRoom();          //初始化选择机房的窗口
        initAddRoom();
        setFMenuListener();         //初始化FMenu的监听器
    }

    public void getItems() {
        this.slidingPaneLayout = findViewById(R.id.home_sliding_layout);
        this.mLeftView = this.slidingPaneLayout.getChildAt(0);
        this.mMainView = this.slidingPaneLayout.getChildAt(1);
        this.fm = findViewById(R.id.activity_home_main_fmenu);
        this.head = findViewById(R.id.activity_home_main_head);
        this.exit = findViewById(R.id.home_left_exit);
        this.course = findViewById(R.id.home_left_course);
        this.exp = findViewById(R.id.home_left_exp);
        this.editinfo = findViewById(R.id.home_left_editinfo);
        this.addroom = findViewById(R.id.home_left_addroom);
        this.signup = findViewById(R.id.home_left_signup);
        this.addStudents = findViewById(R.id.home_left_addStudents);
        this.addCChoose = findViewById(R.id.home_left_addCChoose);
        this.headText = findViewById(R.id.activity_home_main_head_text);
        this.course_img = (ImageView) this.course.getChildAt(0);
        this.course_text = (TextView) this.course.getChildAt(1);
        this.exp_img = (ImageView) this.exp.getChildAt(0);
        this.exp_text = (TextView) this.exp.getChildAt(1);
        this.fb_refresh = findViewById(R.id.activity_home_main_fbutton_refresh);
        this.fb_addexp = findViewById(R.id.activity_home_main_fbutton_addexp);
        recyclerView = findViewById(R.id.activity_home_main_list_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        course_data = new ArrayList<>();
        exp_data = new ArrayList<>();
        course_adapter = new MainListAdapter(this, course_data);
        exp_adapter = new MainListAdapter(this, exp_data);
        status = ALLCOURSE;
        roomIds = new ArrayList<>();
        roomAdapter = new RoomListAdapter(this, roomIds);
        allRoomIds = new ArrayList<>();
        allRoomAdapter = new ChooseRoomListAdapter(this, allRoomIds);
        uInfo = getIntent().getStringExtra("email");

        LayoutInflater inflater = Activity_home.this.getLayoutInflater();
        this.deletExpOrCourseBuilder = new AlertDialog.Builder(Activity_home.this);
        this.viewDeletExpOrCourse = inflater.inflate(R.layout.pop_dialog_delet_exporcourse, null,false);
        this.deletExpOrCourseBuilder.setView(viewDeletExpOrCourse);
        this.deletExpOrCourseBuilder.setCancelable(true);
        this.deletExpOrCourse = this.deletExpOrCourseBuilder.create();

    }

    @SuppressLint("SetTextI18n")
    public void setText() {
        Intent intent = getIntent();
        TextView hello = findViewById(R.id.home_left_hello);
        TextView email = findViewById(R.id.home_left_email);
        hello.setText("Hello," + intent.getStringExtra("usn") + "!");
        email.setText(intent.getStringExtra("email"));
        headText.setText("所有课程");
    }

    public void setSlidingStyle() {
        slidingPaneLayout.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() {
            @Override
            public void onPanelSlide(@NonNull View panel, float slideOffset) {
                //滑动窗格的位置更改时调用
                //设置侧边栏缩放
                mLeftView.setPivotX(-mLeftView.getWidth() / 6.0f);
                mLeftView.setPivotY(mLeftView.getHeight() / 2.0f);
                mLeftView.setScaleX(0.7f + 0.3f * slideOffset);
                mLeftView.setScaleY(0.7f + 0.3f * slideOffset);
                mMainView.setScaleX(1f - 0.2f * slideOffset);
                mMainView.setScaleY(1f - 0.2f * slideOffset);
                mMainView.setElevation(6.0f * slideOffset);
            }
            @Override
            public void onPanelOpened(@NonNull View panel) {
                //在滑动窗格完全打开时调用
                fm.collapse();
            }
            @Override
            public void onPanelClosed(@NonNull View panel) {
                //当滑动窗格完全关闭时调用
            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    public void setHeadButtonListener () {
        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean isOpen = slidingPaneLayout.isOpen();
                if (isOpen) {
                    slidingPaneLayout.closePane();
                } else {
                    slidingPaneLayout.openPane();
                }

            }
        });
    }



    @SuppressLint("ClickableViewAccessibility")
    public void setLeftButtons() {
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((TextView) viewDeletExpOrCourse.findViewById(R.id.pop_dialog_head_text)).setText("退出登录");
                viewDeletExpOrCourse.findViewById(R.id.pop_dialog_del_button_sure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Activity_home.this, Activity_SignIn.class);
                        startActivity(intent);
                        finish();
                    }
                });
                deletExpOrCourse.show();
            }
        });
        course.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                status = ALLCOURSE;
                setLeftCourse();
                resetLeftExp();
                refreshCourse();
                headText.setText("所有课程");
                slidingPaneLayout.closePane();
            }
        });
        exp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                status = ALLEXP;
                setLeftExp();
                resetLeftCourse();
                refreshExp();
                headText.setText("所有实验");
                slidingPaneLayout.closePane();
            }
        });
        editinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent info = getIntent();
                Intent intent = new Intent(Activity_home.this, Activity_EditUserInfo.class);
                intent.putExtra("usn", info.getStringExtra("usn"));
                intent.putExtra("psw", info.getStringExtra("psw"));
                intent.putExtra("email", uInfo);
                startActivity(intent);
            }
        });
        addroom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addRoom.show();
            }
        });
        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Activity_home.this, Activity_SignUp.class);
                startActivity(intent);
            }
        });
        addStudents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 0);
            }
        });
        addCChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 1);
            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
        if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
            Uri uri = resultData.getData();
            try {
                InputStream is = getContentResolver().openInputStream(uri);
                File cache = new File(Activity_home.this.getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(), "hbhdfjy.xls");
                FileOutputStream fos = new FileOutputStream(cache);
                FileUtils.copy(is, fos);
                fos.close();
                is.close();
                addStudents(cache, 0);
            } catch (IOException e){
                e.printStackTrace();
            }
        } else if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            Uri uri = resultData.getData();
            try {
                InputStream is = getContentResolver().openInputStream(uri);
                File cache = new File(Activity_home.this.getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath(), "hbhdfjy.xls");
                FileOutputStream fos = new FileOutputStream(cache);
                FileUtils.copy(is, fos);
                fos.close();
                is.close();
                addStudents(cache, 1);
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, resultData);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void setLeftCourse() {
        course.setBackground(getResources().getDrawable(R.drawable.button_choosing_right));
        course_img.setImageResource(R.drawable.course_main_dark);
        course_text.setTextColor(getResources().getColor(R.color.mainColor_dark));
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void resetLeftCourse() {
        course.setBackground(getResources().getDrawable(R.drawable.button_press));
        course_img.setImageResource(R.drawable.course_black);
        course_text.setTextColor(getResources().getColor(R.color.black));
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void setLeftExp() {
        exp.setBackground(getResources().getDrawable(R.drawable.button_choosing_right));
        exp_img.setImageResource(R.drawable.exp_main_dark);
        exp_text.setTextColor(getResources().getColor(R.color.mainColor_dark));
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    public void resetLeftExp() {
        exp.setBackground(getResources().getDrawable(R.drawable.button_press));
        exp_img.setImageResource(R.drawable.exp_black);
        exp_text.setTextColor(getResources().getColor(R.color.black));
    }

    private void initViewItemListener() {
        viewDeletExpOrCourse.findViewById(R.id.pop_dialog_del_button_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deletExpOrCourse.dismiss();
            }
        });
        exp_adapter.setOnItemClickListener(new MainListAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(View view, int position) {
                expId = exp_data.get(position).sNumber;
                expName = exp_data.get(position).name;
                getRooms();
            }
        });
        exp_adapter.setOnLongClickListener(new MainListAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                ((TextView) viewDeletExpOrCourse.findViewById(R.id.pop_dialog_head_text)).setText("确认删除实验");
                viewDeletExpOrCourse.findViewById(R.id.pop_dialog_del_button_sure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        deletCourseOrExp(exp_data.get(position).sNumber, 1);
                        deletExpOrCourse.dismiss();
                    }
                });
                deletExpOrCourse.show();
            }
        });
        course_adapter.setOnItemClickListener(new MainListAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(View view, int position) {
                status = EXP;
                courseId = course_data.get(position).sNumber;
                headText.setText(course_data.get(position).name);
                refreshExp(courseId);
            }
        });
        course_adapter.setOnLongClickListener(new MainListAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                ((TextView) viewDeletExpOrCourse.findViewById(R.id.pop_dialog_head_text)).setText("确认删除课程");
                viewDeletExpOrCourse.findViewById(R.id.pop_dialog_del_button_sure).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        deletCourseOrExp(course_data.get(position).sNumber, 0);
                        deletExpOrCourse.dismiss();
                    }
                });
                deletExpOrCourse.show();
            }
        });
    }

    private void initView() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        refreshCourse();
    }

    public void setFMenuListener() {
        fb_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (status == ALLCOURSE) {
                    refreshCourse();
                } else if (status == ALLEXP) {
                    refreshExp();
                } else if (status == EXP) {
                    refreshExp(courseId);
                }
                fm.collapse();
            }
        });
        fb_addexp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (status == ALLCOURSE) {
                    ((EditText) viewAddCourse.findViewById(R.id.pop_dialog_addcourse_head_courseid)).setText("");
                    ((EditText) viewAddCourse.findViewById(R.id.pop_dialog_addcourse_head_coursename)).setText("");
                    addCourse.show();
                } else if (status == EXP) {
                    ((EditText) viewAddExp.findViewById(R.id.pop_dialog_addexp_head_edittext)).setText("");
                    getAllRooms();
                } else if (status == ALLEXP) {
                    Toast.makeText(getBaseContext(), "请在具体课程中添加实验", Toast.LENGTH_SHORT).show();
                }
                fm.collapse();
            }
        });
    }

    public void initAddExp() {
        this.addExpBuilder = new AlertDialog.Builder(Activity_home.this);
        LayoutInflater inflater = Activity_home.this.getLayoutInflater();
        this.viewAddExp = inflater.inflate(R.layout.pop_dialog_addexp, null,false);
        this.addExpBuilder.setView(viewAddExp);
        this.addExpBuilder.setCancelable(true);
        this.addExp = this.addExpBuilder.create();
        RecyclerView rv = (RecyclerView) viewAddExp.findViewById(R.id.pop_dialog_addexp_rv);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(allRoomAdapter);
        allRoomAdapter.setOnItemClickListener(new ChooseRoomListAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(View view, int position) {
                if (allRoomIds.get(position).ifChecked) {
                    allRoomIds.get(position).ifChecked = false;
                } else {
                    allRoomIds.get(position).ifChecked = true;
                }
                allRoomAdapter.notifyDataSetChanged();
            }
        });
        viewAddExp.findViewById(R.id.pop_dialog_addexp_button_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addExp.dismiss();
            }
        });
        viewAddExp.findViewById(R.id.pop_dialog_addexp_button_addexp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ArrayList<String> finalChoose = new ArrayList<>();
                EditText text = viewAddExp.findViewById(R.id.pop_dialog_addexp_head_edittext);
                for (ChooseRoomListItemBean room : allRoomIds) {
                    if (room.ifChecked) {
                        finalChoose.add(room.roomId);
                    }
                }
                addExp(text.getText().toString(), finalChoose);
                addExp.dismiss();
            }
        });
    }

    public void initAddCourse() {
        this.addCourseBuilder = new AlertDialog.Builder(Activity_home.this);
        LayoutInflater inflater = Activity_home.this.getLayoutInflater();
        this.viewAddCourse = inflater.inflate(R.layout.pop_dialog_addcourse, null,false);
        this.addCourseBuilder.setView(viewAddCourse);
        this.addCourseBuilder.setCancelable(true);
        this.addCourse = this.addCourseBuilder.create();
        NumberPicker year = viewAddCourse.findViewById(R.id.pop_dialog_addcourse_head_courseseminar_year);
        NumberPicker season = viewAddCourse.findViewById(R.id.pop_dialog_addcourse_head_courseseminar_season);
        season.setDisplayedValues(seasons);
        season.setMinValue(0);
        season.setMaxValue(seasons.length - 1);
        year.setMaxValue(2030);
        year.setMinValue(2010);
        viewAddCourse.findViewById(R.id.pop_dialog_addcourse_button_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addCourse.dismiss();
            }
        });
        viewAddCourse.findViewById(R.id.pop_dialog_addcourse_button_addcourse).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText name = viewAddCourse.findViewById(R.id.pop_dialog_addcourse_head_coursename);
                EditText id = viewAddCourse.findViewById(R.id.pop_dialog_addcourse_head_courseid);
                addCourse(name.getText().toString(), id.getText().toString(), year.getValue(), season.getValue());
                addCourse.dismiss();
            }
        });
    }

    public void initAddRoom() {
        this.addRoomBuilder = new AlertDialog.Builder(Activity_home.this);
        LayoutInflater inflater = Activity_home.this.getLayoutInflater();
        this.viewAddRoom = inflater.inflate(R.layout.pop_dialog_addroom, null,false);
        this.addRoomBuilder.setView(viewAddRoom);
        this.addRoomBuilder.setCancelable(true);
        this.addRoom = this.addRoomBuilder.create();
        NumberPicker np = viewAddRoom.findViewById(R.id.pop_dialog_addroom_head_seatnum);
        np.setMinValue(1);
        np.setMaxValue(100);
        viewAddRoom.findViewById(R.id.pop_dialog_addroom_button_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NumberPicker np = ((NumberPicker) viewAddRoom.findViewById(R.id.pop_dialog_addroom_head_seatnum));
                EditText et = ((EditText) viewAddRoom.findViewById(R.id.pop_dialog_addroom_head_edittext));
                addRoom.dismiss();
                et.setText("");
                np.setValue(1);
            }
        });
        viewAddRoom.findViewById(R.id.pop_dialog_addroom_button_addroom).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NumberPicker np = ((NumberPicker) viewAddRoom.findViewById(R.id.pop_dialog_addroom_head_seatnum));
                EditText et = ((EditText) viewAddRoom.findViewById(R.id.pop_dialog_addroom_head_edittext));
                addRoom(et.getText().toString(), np.getValue());
                addRoom.dismiss();
                et.setText("");
                np.setValue(1);
            }
        });
    }

    public void initChooseCRoom() {
        this.chooseCRoomBuilder = new AlertDialog.Builder(Activity_home.this);
        LayoutInflater inflater = Activity_home.this.getLayoutInflater();
        this.viewChooseCRoom = inflater.inflate(R.layout.pop_dialog_choosecroom, null,false);
        chooseCRoomBuilder.setView(viewChooseCRoom);
        chooseCRoomBuilder.setCancelable(true);
        this.chooseCRoom = this.chooseCRoomBuilder.create();
        RecyclerView rv = viewChooseCRoom.findViewById(R.id.pop_dialog_choosecroom_recyclerview);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setAdapter(roomAdapter);
    }


    public void refreshExp(String cours_id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                exp_data = HttpUnit.getExpByCourseID(cours_id);
                runOnUiThread(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        if (exp_data == null) {
                            Toast.makeText(getBaseContext(), "获取实验信息错误", Toast.LENGTH_SHORT).show();
                        } else {
                            exp_adapter.data = exp_data;
                            recyclerView.setAdapter(exp_adapter);
                            exp_adapter.notifyDataSetChanged();

                        }
                    }
                });
            }
        }).start();
    }

    public void refreshExp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                exp_data = HttpUnit.getExpByCourseID(null);
                runOnUiThread(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        if (exp_data == null) {
                            Toast.makeText(getBaseContext(), "获取所有实验信息错误", Toast.LENGTH_SHORT).show();
                        } else {
                            exp_adapter.data = exp_data;
                            recyclerView.setAdapter(exp_adapter);
                            exp_adapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }).start();
    }

    public void refreshCourse() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                course_data = getAllCourse();
                runOnUiThread(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        if (course_data == null) {
                            Toast.makeText(getBaseContext(), "获取课程信息错误", Toast.LENGTH_SHORT).show();
                        } else {
                            course_adapter.data = course_data;
                            recyclerView.setAdapter(course_adapter);
                            course_adapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }).start();
    }

    public void addExp(String expName, ArrayList<String> rooms) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean succeed = HttpUnit.addExperiment(expName, courseId, rooms);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (succeed) {
                            refreshExp(courseId);
                        } else {
                            Toast.makeText(getBaseContext(), "新建失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public void addCourse(String courseName, String id, int year, int season) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean succeed = HttpUnit.addCourse(id, year, season, courseName);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (succeed) {
                            refreshCourse();
                        } else {
                            Toast.makeText(getBaseContext(), "新建失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public void deletCourseOrExp(String id, int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean succeed = HttpUnit.delCourseOrExp(id, i);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (succeed) {
                            if (i == 0) {
                                refreshCourse();
                            } else {
                                refreshExp(courseId);
                            }
                        } else {
                            Toast.makeText(getBaseContext(), "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public void addRoom(String name, int seatNum) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean succeed = HttpUnit.addClassroom(name, seatNum);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (succeed) {
                            Toast.makeText(getBaseContext(), "添加成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getBaseContext(), "添加失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public void getAllRooms() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> rooms = HttpUnit.getAllClassrooms();
                runOnUiThread(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        if (rooms != null) {
                            allRoomIds = new ArrayList<>();
                            for (String id : rooms) {
                                allRoomIds.add(new ChooseRoomListItemBean(id));
                            }
                            allRoomAdapter.data = allRoomIds;
                            allRoomAdapter.notifyDataSetChanged();
                            addExp.show();
                        } else {
                            Toast.makeText(getBaseContext(), "获取所有机房失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    public void getRooms() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> rooms = HttpUnit.getClassroomsFromExp(expId);
                runOnUiThread(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        if (rooms == null) {
                            Toast.makeText(getBaseContext(), "获取机房失败", Toast.LENGTH_SHORT).show();
                        } else {
                            roomAdapter.setOnItemClickListener(new RoomListAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    Intent intent = new Intent(Activity_home.this, Activity_ExpInfo.class);
                                    intent.putExtra("expName", expName);
                                    intent.putExtra("expId", expId);
                                    intent.putExtra("roomId", roomIds.get(position));
                                    startActivity(intent);
                                    chooseCRoom.dismiss();
                                }
                            });
                            roomIds = rooms;
                            roomAdapter.data = roomIds;
                            roomAdapter.notifyDataSetChanged();
                            chooseCRoom.show();
                        }
                    }
                });
            }
        }).start();
    }

    public void getEmail() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Intent i = getIntent();
                UserInfo info = HttpUnit.getUserInfoByUsername(i.getStringExtra("usn"));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView email = findViewById(R.id.home_left_email);
                        if (info == null) {
                            Toast.makeText(getBaseContext(), "获取用户信息失败", Toast.LENGTH_SHORT).show();
                        } else {
                            email.setText(info.email);
                            uInfo = info.email;
                        }
                    }
                });
            }
        }).start();
    }

    public void addStudents(File file, int status) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean success = HttpUnit.addStudentByXls(file, status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (success) {
                            Toast.makeText(getBaseContext(), "导入学生信息成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getBaseContext(), "导入学生信息失败", Toast.LENGTH_SHORT).show();}
                    }
                });
            }
        }).start();
    }

    @Override
    public boolean onKeyDown(int KeyCode, KeyEvent event) {
        if (status == EXP) {
            refreshCourse();
            status = ALLCOURSE;
            headText.setText("所有课程");
            return true;
        }
        return super.onKeyDown(KeyCode, event);
    }

    @Override
    protected void onResume() {
        getEmail();
        super.onResume();
    }
}